import 'package:bilibili/http/core/hi_error.dart';
import 'package:bilibili/http/core/hi_net_adapter.dart';
import 'package:bilibili/http/request/base_request.dart';
import 'package:dio/dio.dart';

class DioAdapter extends HiNetAdapter {
  @override
  Future<HiNetResponse<T>> send<T>(BaseRequest request) async {
    Response? response;
    DioException? error;

    var options = Options(headers: request.header);

    try {
      if (request.httpMethod() == HttpMehtod.GET) {
        response = await Dio().get(request.url().toString(), options: options);
      } else if (request.httpMethod() == HttpMehtod.POST) {
        response = await Dio().post(request.url().toString(),
            options: options, data: request.params);
      } else if (request.httpMethod() == HttpMehtod.DELETE) {
        response =
            await Dio().delete(request.url().toString(), options: options);
      } else if (request.httpMethod() == HttpMehtod.PATCH) {
        response =
            await Dio().patch(request.url().toString(), options: options);
      }
    } on DioException catch (e) {
      error = e;
      response = e.response;
    }

    if (error != null) {
      throw HiNetError(response?.statusCode ?? -1, error.toString(),
          data: HiNetResponse(
              data: response?.data ?? "",
              request: request,
              statusCode: response?.statusCode ?? -1));
    }

    return buildRes(response!, request);
  }

  // 构建HiNetResponse
  Future<HiNetResponse<T>> buildRes<T>(Response response, BaseRequest request) {
    return Future.value(HiNetResponse(
        data: response.data,
        request: request,
        statusCode: response.statusCode));
  }
}
